package com.xindaoapp.happypet.adapter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.activity.IwantJoinActivity;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.activity.MyClubActivity;
import com.xindaoapp.happypet.activity.PostImageActivity;
import com.xindaoapp.happypet.api.ConstantsValue;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.PostLandlordInfo;
import com.xindaoapp.happypet.bean.PostLandlordInfo.ActivityInfo;
import com.xindaoapp.happypet.bean.PostLandlordMessageInfo;
import com.xindaoapp.happypet.bean.PostLayerInfo;
import com.xindaoapp.happypet.bean.PostLayerInfos;
import com.xindaoapp.happypet.bean.RecommendInfo;
import com.xindaoapp.happypet.entry.ReturnClass;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.ui.PostDetailActivity;
import com.xindaoapp.happypet.ui.WebViewActivity;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.xdConfig;
import com.xindaoapp.happypet.view.MxxBlurView;
import com.xindaoapp.happypet.view.MyTestVideoView;

/**
 * 帖子详情适配器
 * 
 * @author chenghao
 * 
 */
public class PostDetailAdapter extends BaseAdapter {

    private final View mFooterLoadingView;
    private final PullToRefreshListView mListView;

    private List<PostLayerInfo> list = new ArrayList<PostLayerInfo>();
    /** 楼主信息 */
    private final List<RecommendInfo> mRecommendInfos;
    /** 标记是否有视频，有视频的时候onStop和onResume的时候需要刷新 */
    /** 对视频布局进行缓存 */
    private final Map<Integer, View> mVideoViews = new HashMap<Integer, View>();
    private final Map<Integer, VideoHolder> mVideoHolderViews = new HashMap<Integer, VideoHolder>();
    private final Activity context;
    private final String tid;
    private final String onlyauthor;
    private final String mPkUid;
    private final PostLandlordInfo mPostLandlordMessageInfo;
    /** 是否是消息中心跳转的详情，true：是，隐藏内容模块，举报按钮区域 */
    private boolean mIsLookDetail;
    private boolean isHasVideo;
    /** 当前播放视频的position */
    private int mPlayVideoPosition = -1;
    private final JoinActivitySuccessReceiver successReceiver;
    private final IRequest<ReturnClass> iRequest;

    public PostDetailAdapter(Activity context, PostLandlordInfo mPostLandlordMessageInfo,
            List<RecommendInfo> mRecommendInfos, String tid, String onlyauthor,
            PullToRefreshListView listView, String mPkUid, IRequest<ReturnClass> request) {
        super();
        this.mPkUid = mPkUid;
        mListView = listView;
        this.mPostLandlordMessageInfo = mPostLandlordMessageInfo;
        this.context = context;
        this.tid = tid;
        this.mRecommendInfos = mRecommendInfos;
        this.onlyauthor = onlyauthor;
        this.iRequest = request;
        if (!TextUtils.isEmpty(mPkUid)) {
            this.mIsLookDetail = true;
        }
        mFooterLoadingView = View.inflate(context, R.layout.item_loading, null);
        successReceiver = new JoinActivitySuccessReceiver();
        context.registerReceiver(successReceiver, new IntentFilter(
                ConstantsValue.JOIN_ACTIVITY_SUCCESS));
    }

    public void resetLayerInfos(List<PostLayerInfo> mList) {
        this.list = mList;
        isLoadingNext = false;
        isHasNextPage = true;
    }

    public void resetLayerInfos(List<PostLayerInfo> mList, int pageNum) {
        this.list = mList;
        isLoadingNext = false;
        isHasNextPage = true;
        pageNumber = pageNum;
    }

    public List<PostLayerInfo> getResult() {
        return list;
    }

    @Override
    public int getCount() {
        return list.size() == 0 ? 1 : list.size() + 1;
    }

    public int getPlayPosition() {
        return mPlayVideoPosition;
    }

    @Override
    public Object getItem(int position) {
        if (position == 0) {
            return mPostLandlordMessageInfo;
        } else {
            return list.get(position - 1);
        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return 0;
        } else if (isVideoItem(position)) {
            return 1;
        } else {
            return 2;
        }
    }

    private boolean isVideoItem(int position) {
        PostLayerInfo info = list.get(position - 1);
        for (int i = 0; i < info.message.size(); i++) {
            // 检查是否含有视频
            if (info.message.get(i).type.equals(VIDEO)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getViewTypeCount() {
        return 3;
    }

    @Override
    public View getView(int position, View contentView, ViewGroup parent) {
        int itemViewType = getItemViewType(position);
        if (itemViewType == 0) {// 楼主
            contentView = mVideoViews.get(contentView);
            if (contentView == null) {
                contentView = initLandlordView(mPostLandlordMessageInfo);
            }
            return contentView;
        } else if (itemViewType == 1 || itemViewType == 2) {
            boolean isHaveVideo = false;
            if (itemViewType == 1) {
                isHaveVideo = true;
                contentView = mVideoViews.get(contentView);
                if (contentView != null) {
                    return contentView;
                }
            }

            ViewHolder holder;
            if (contentView == null) {
                holder = new ViewHolder();
                contentView = View.inflate(context, R.layout.item_post, null);
                holder.icon = (ImageView) contentView.findViewById(R.id.icon);
                holder.name = (TextView) contentView.findViewById(R.id.name);
                holder.address = (TextView) contentView.findViewById(R.id.address);
                holder.floor = (TextView) contentView.findViewById(R.id.floor);
                holder.time = (TextView) contentView.findViewById(R.id.time);
                holder.report = contentView.findViewById(R.id.jubao_louzhu);
                holder.reply = contentView.findViewById(R.id.huifu_louzhu);
                holder.louzhuLogo = contentView.findViewById(R.id.persion_louzhu);
                holder.container = (LinearLayout) contentView.findViewById(R.id.container);
                holder.persion_position =
                        (ImageView) contentView.findViewById(R.id.persion_position);
                contentView.setTag(holder);
            } else {
                holder = (ViewHolder) contentView.getTag();
            }
            PostLayerInfo info = list.get(position - 1);

            ImageLoader.getInstance().displayImage(info.userface, holder.icon);
            holder.name.setText(info.author);
            holder.address.setText(String.format(context.getString(R.string.come_from),
                    info.address));
            holder.floor.setText(String.format("%s楼", info.position));
            if (holder.floor.getText().toString().trim().equals("2楼")) {
                holder.floor.setText("沙发");
            } else if (holder.floor.getText().toString().trim().equals("3楼")) {
                holder.floor.setText("板凳");
            } else if (holder.floor.getText().toString().trim().equals("4楼")) {
                holder.floor.setText("地板");
            }

            if (mPostLandlordMessageInfo.authorid.equals(info.authorid)) {
                holder.louzhuLogo.setVisibility(View.VISIBLE);
            } else {
                holder.louzhuLogo.setVisibility(View.GONE);
            }

            setPersionPermission(holder.persion_position, info.member_groupid);

            String time = CommonUtil.formatDate();
            String year = time.substring(0, 4);

            String mTime = info.addtime;
            String mYear = mTime.substring(0, 4);

            String today = mTime.split(" ")[1];
            if (year.equals(mYear)) {// 说明是今年
                if (mTime.split(" ")[0].equals(time.split(" ")[0])) {// 说明是今天
                    holder.time.setText(today.substring(0, 5));
                } else {
                    holder.time.setText(info.addtime.split(" ")[0].substring(5, 10) + " "
                            + today.substring(0, 5));
                }
            } else {
                holder.time.setText(mTime.split(" ")[0]);
            }

            setReportListener(holder.report, info.pid);
            setReplyListener(holder.reply, info.position, info.pid);
            setStartUserInfoActivityListener(holder.icon, info.authorid, info.author, info.userface);

            parsePostContainer(holder.container, info.message, position);
            if (getCount() - 9 == position) {
                nextPage();
            }
            if (isHaveVideo) {
                mVideoViews.put(position, contentView);
            }
        }
        return contentView;
    }

    private void setReportListener(View view, final String pid) {
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(context).setTitle("举报").setMessage("确认要举报吗?")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (UserState.isLogged(context)) {
                                    getData(pid);
                                }
                                dialog.dismiss();
                            }
                        }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {}
                        }).create().show();
            }
        });
    }

    private void setReplyListener(View view, final String position, final String pid) {
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (UserState.isLogged(context)) {
                    ReturnClass t = new ReturnClass();
                    t.mPid = pid;
                    t.foolder = position;
                    iRequest.request(t);
                }
            }
        });
    }

    private void setStartUserInfoActivityListener(View view, final String uid, final String name,
            final String face) {
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(context, MainActivity.class);
                intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                        UserInfoFragment.class.getCanonicalName());
                Bundle bundle = new Bundle();
                bundle.putString(Constants.KEY_UID, uid);
                bundle.putString(Constants.KEY_USERNAME, name);
                bundle.putString(Constants.KEY_USERFACE, face);
                intent.putExtra(Constants.KEY_BUNDLE, bundle);
                context.startActivity(intent);
            }
        });
    }

    class ViewHolder {
        ImageView icon;
        TextView name;
        TextView address;
        TextView floor;
        TextView time;
        View report;
        View reply;
        LinearLayout container;
        MyTestVideoView myTestVideoView;
        ImageView persion_position;
        View louzhuLogo;
    }

    private int pageNumber = 1;

    private boolean isLoadingNext;
    private boolean isHasNextPage = true;

    private void nextPage() {
        nextPage(null);
    }

    public void nextPage(final IRequest<Boolean> iRequest) {
        if (iRequest == null) {
            if (isLoadingNext || !isHasNextPage) {
                return;
            }
        }
        mListView.getRefreshableView().addFooterView(mFooterLoadingView);
        isLoadingNext = true;
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getPostLayerDetail(UserState.getUserUid(), tid, onlyauthor, mPkUid, ++pageNumber,
                        Constants.PAGE_SIZE, 0, new IRequest<PostLayerInfos>() {

                            @Override
                            public void request(PostLayerInfos t) {
                                mListView.getRefreshableView().removeFooterView(mFooterLoadingView);
                                if (null != t) {
                                    getResult().addAll(t.postarray);
                                    notifyDataSetChanged();
                                    isLoadingNext = false;
                                    if (t.postarray.size() < Constants.PAGE_SIZE) {
                                        isHasNextPage = false;
                                    } else {
                                        isHasNextPage = true;
                                    }
                                    if (t.postarray.size() == 0) {
                                        pageNumber--;
                                        if (iRequest != null) {
                                            iRequest.request(false);
                                        }
                                    } else {
                                        if (iRequest != null) {
                                            iRequest.request(true);
                                        }
                                    }
                                } else {
                                    pageNumber--;
                                    if (iRequest != null) {
                                        iRequest.request(false);
                                    }
                                    isLoadingNext = false;
                                    isHasNextPage = false;
                                }
                            }
                        });
    }

    private void getData(String pid) {
        if (CommonUtil.checkNetState(context)) {
            RequestParams params = new RequestParams();
            params.put("tid", tid);
            params.put("uid", UserState.getUserUid());
            params.put("pid", pid);

            XDHttpClient.get(xdConfig.PRAISEPOST, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    int result = -1;
                    JSONObject obj;
                    try {
                        obj = new JSONObject(content);
                        result = obj.getInt("result");
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }

                    if (result == 0) {
                        Toast.makeText(context, "举报成功", Toast.LENGTH_SHORT).show();
                    } else if (result == 2) {
                        Toast.makeText(context, "已举报", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, R.string.get_jubao_error_data, Toast.LENGTH_SHORT)
                                .show();
                    }
                }

                @Override
                public void onFailure(Throwable arg0, String arg1) {
                    super.onFailure(arg0, arg1);
                    Toast.makeText(context, R.string.get_error_data, Toast.LENGTH_SHORT).show();
                }
            });

        } else {
            Toast.makeText(context, R.string.pLease_check_network, Toast.LENGTH_SHORT).show();
            return;
        }
    }

    private final OnClickListener mPraiseOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (UserState.isLogged(context)) {
                praise.setEnabled(false);
                if (mPostLandlordMessageInfo.myrecommend == 1) {
                    praise.setEnabled(true);
                    Toast.makeText(context, "已赞过", Toast.LENGTH_SHORT).show();
                } else {
                    getCareData();
                }
            }
        }
    };

    /**
     * 是否赞过
     */
    private void getCareData() {// 获取点赞数据
        if (CommonUtil.checkNetState(context)) {
            RequestParams params = new RequestParams();
            params.put("tid", tid);
            params.put("uid", UserState.getUserUid());
            XDHttpClient.get(xdConfig.PRAISEPOST, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    praise.setEnabled(true);
                    try {
                        if (new JSONObject(content).getInt("result") == 0) {
                            RecommendInfo info = new RecommendInfo();
                            info.setUserface(UserState.getUser().userface);
                            mRecommendInfos.add(0, info);
                            mPostLandlordMessageInfo.myrecommend = 1;
                            mPostLandlordMessageInfo.recommend_add++;
                            Toast.makeText(context, "点赞成功", Toast.LENGTH_SHORT).show();
                            notifyDataSetChanged();
                        } else {
                            Toast.makeText(context, "点赞失败", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Throwable arg0, String arg1) {
                    super.onFailure(arg0, arg1);
                    praise.setEnabled(true);
                    Toast.makeText(context, R.string.get_error_data, Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            praise.setEnabled(true);
            Toast.makeText(context, R.string.pLease_check_network, Toast.LENGTH_SHORT).show();
            return;
        }
    }

    // **********************************************************************
    private LinearLayout ll_activity;
    private LinearLayout ll_time;
    private LinearLayout ll_location;
    private LinearLayout ll_done;
    private LinearLayout ll_view;
    private TextView starttime;
    private TextView location;
    private TextView done;
    private TextView views;
    private TextView applynumber;
    private TextView join;

    public PostLandlordInfo getPostLandlordInfo() {
        return mPostLandlordMessageInfo;
    }

    /**
     * 1为管理员，2为版主，3为版主
     * 
     * @param icon
     * @param memberGroupid
     */
    private void setPersionPermission(ImageView icon, int memberGroupid) {
        if (memberGroupid == 1) {
            icon.setVisibility(View.VISIBLE);
            icon.setImageResource(R.drawable.guanli);
        } else if (memberGroupid == 2) {
            icon.setVisibility(View.VISIBLE);
            icon.setImageResource(R.drawable.banzhu);
        } else if (memberGroupid == 3) {
            icon.setVisibility(View.VISIBLE);
            icon.setImageResource(R.drawable.banzhu);
        } else {
            icon.setVisibility(View.INVISIBLE);
        }
    }

    private void initLookState(final View lookMore, final View closeMore, final PostLandlordInfo t) {

        if (isShowing) {
            closeMore.findViewById(R.id.look).setVisibility(View.VISIBLE);
            closeMore.setVisibility(View.VISIBLE);
        } else {

        }

        lookMore.findViewById(R.id.look_more).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                isShowing = true;
                closeMore.findViewById(R.id.look).setVisibility(View.VISIBLE);
                closeMore.setVisibility(View.VISIBLE);
                lookMore.setVisibility(View.GONE);
            }
        });
        lookMore.findViewById(R.id.look_theme).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // 查看主题帖
                Intent i = new Intent(context, PostDetailActivity.class);
                i.putExtra(Constants.KEY_POST_TID, t.tid);
                context.startActivity(i);
            }
        });

        closeMore.findViewById(R.id.look_more).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                isShowing = false;
                closeMore.setVisibility(View.GONE);
                lookMore.setVisibility(View.VISIBLE);
            }
        });
        closeMore.findViewById(R.id.look_theme).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // 查看主题帖
                Intent i = new Intent(context, PostDetailActivity.class);
                i.putExtra(Constants.KEY_POST_TID, t.tid);
                context.startActivity(i);
            }
        });
    }

    /**
     * 是否已经展开
     */
    private boolean isShowing;

    /**
     * 初始化楼主
     * 
     * @param t
     * @return
     */
    private View initLandlordView(final PostLandlordInfo t) {
        View view = View.inflate(context, R.layout.item_post_landlord, null);
        ImageView iv_top_image = (ImageView) view.findViewById(R.id.iv_top_image);
        View include = view.findViewById(R.id.include);
        if (null != t.activityinfo && t.activityinfo.acttype.equals("shiyong")) {
            iv_top_image.setVisibility(View.VISIBLE);
        } else {
            iv_top_image.setVisibility(View.GONE);
        }
        int coverwidth = 1;
        int coverheight = 1;
        if (t != null && t.activityinfo != null) {
            try {
                coverwidth = Integer.parseInt(t.activityinfo.coverwidth);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            try {
                coverheight = Integer.parseInt(t.activityinfo.coverheight);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        iv_top_image.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                (int) ((float) CommonParameter.sScreenWidth / coverwidth * coverheight)));
        if (t != null && t.activityinfo != null && !TextUtils.isEmpty(t.activityinfo.coverpath)) {
            ImageLoader.getInstance().displayImage(t.activityinfo.coverpath, iv_top_image);
        } else {
            iv_top_image.setImageResource(R.drawable.picture_loading);
        }


        // View post_top_1 = view.findViewById(R.id.post_top_1);
        // View post_top_2 = view.findViewById(R.id.post_top_2);
        // TextView vActclass = (TextView) view.findViewById(R.id.tv_actclass);
        // View p_2 = view.findViewById(R.id.p_2);

        // 区分申请使用帖子头布局
        // if (null != t.activityinfo && t.activityinfo.acttype.equals("shiyong")) {
        // post_top_1.setVisibility(View.GONE);
        // post_top_2.setVisibility(View.VISIBLE);
        // p_2.setVisibility(View.GONE);
        // vActclass.setText(t.activityinfo.actclass);
        //
        // item_post_top_info(t, view, coverwidth, coverheight);
        //
        // } else {
        // post_top_1.setVisibility(View.VISIBLE);
        // post_top_2.setVisibility(View.GONE);
        // p_2.setVisibility(View.VISIBLE);
        // }


        try {// 可能出现 java.io.FileNotFoundException: emoji.xml
            ((TextView) view.findViewById(R.id.post_name)).setText(CommonUtil.convetToHtml(
                    CommonUtil.parseEmoji(t.subject), context));
            // ((TextView) view.findViewById(R.id.post_name)).setText(ParseMsgUtil.convetToHtml(
            // CommonUtil.parseEmoji(CommonUtil.parseStr(t.subject)), context));
            // holder.content.setText();
        } catch (Exception e) {
            e.printStackTrace();
        }

        final View closeMore = view.findViewById(R.id.l_close_more);
        final View lookMore = view.findViewById(R.id.l_look_more);

        parsePostContainer((LinearLayout) view.findViewById(R.id.container), t.message, 0);
        if (mIsLookDetail) {

            (view.findViewById(R.id.function_jubao)).setVisibility(View.GONE);

            ((TextView) lookMore.findViewById(R.id.title)).setText(t.subject);

            if (isShowing) {
                closeMore.setVisibility(View.VISIBLE);
                lookMore.setVisibility(View.GONE);
            } else {
                closeMore.setVisibility(View.GONE);
                lookMore.setVisibility(View.VISIBLE);
            }

            initLookState(lookMore, closeMore, t);
        } else {
            lookMore.setVisibility(View.GONE);
            closeMore.setVisibility(View.VISIBLE);
        }

        // 隐藏回复按钮
        view.findViewById(R.id.huifu_louzhu).setVisibility(View.GONE);

        setPersionPermission(((ImageView) view.findViewById(R.id.persion_position)),
                t.member_groupid);

        ((TextView) view.findViewById(R.id.tv_zan)).setText(String.format("等%s人赞过帖子",
                t.recommend_add));

        (view.findViewById(R.id.persion_louzhu)).setVisibility(View.VISIBLE);

        praise = (TextView) view.findViewById(R.id.zanyixia);
        praise.setVisibility(View.VISIBLE);
        praise.setOnClickListener(mPraiseOnClickListener);

        if (t.myrecommend == 1) {
            praise.setText("已赞");
            praise.setSelected(true);
        } else {
            praise.setText("赞一下");
            praise.setSelected(false);
        }

        String temp = t.forumname;
        if (t.forumname.lastIndexOf("俱乐部") >= 0) {
            temp = temp.substring(0, t.forumname.length() - 3);
        }
        if (null != t.activityinfo && t.activityinfo.acttype.equals("shiyong")) {
            include.setVisibility(View.GONE);
            ((TextView) view.findViewById(R.id.post_address)).setText(t.activityinfo.actclass);
        } else {
            include.setVisibility(View.VISIBLE);
            ((TextView) view.findViewById(R.id.post_address)).setText(temp);

        }
        ll_time = (LinearLayout) view.findViewById(R.id.ll_time);
        ll_location = (LinearLayout) view.findViewById(R.id.ll_location);
        ll_done = (LinearLayout) view.findViewById(R.id.ll_done);
        ll_view = (LinearLayout) view.findViewById(R.id.ll_view);
        ll_activity = (LinearLayout) view.findViewById(R.id.ll_activity);

        starttime = (TextView) view.findViewById(R.id.starttime);
        location = (TextView) view.findViewById(R.id.location);
        done = (TextView) view.findViewById(R.id.done);
        views = (TextView) view.findViewById(R.id.views);
        applynumber = (TextView) view.findViewById(R.id.applynumber);
        join = (TextView) view.findViewById(R.id.join);

        if (t != null && t.activityinfo != null) {

            if (TextUtils.isEmpty(t.activityinfo.acttype)) {
                join.setVisibility(View.VISIBLE);
            } else if (t.activityinfo.acttype.equals("shiyong")) {
                join.setVisibility(View.GONE);
            } else if (t.activityinfo.acttype.equals("huati")) {
                join.setVisibility(View.GONE);

            }
            ll_activity.setVisibility(View.VISIBLE);
            ActivityInfo info = t.activityinfo;
            if (!TextUtils.isEmpty(info.starttimefrom)) {
                starttime.setText(info.starttimefrom + "");
            } else {
                ll_time.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(info.place)) {
                location.setText(info.place);
            } else {
                ll_location.setVisibility(View.GONE);
            }
            if (null != t.activityinfo.isapply && t.activityinfo.isapply.equals("1")) {
                join.setBackgroundResource(R.drawable.join_noclick);
            } else if (null != t.activityinfo.isapply && t.activityinfo.isapply.equals("0")) {
                join.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, IwantJoinActivity.class);
                        intent.putExtra("info", t);
                        context.startActivity(intent);
                    }
                });
            }
            if (!TextUtils.isEmpty(info.expiration)) {
                if (info.expiration.equals("0")) {
                    ll_done.setVisibility(View.GONE);
                } else {
                    done.setText(info.expiration + "");
                    if (parserDate(info.expiration) < System.currentTimeMillis()) {
                        join.setBackgroundResource(R.drawable.join_noclick);
                        join.setClickable(false);
                    }
                }
            } else {
                ll_done.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(info.applynumber)) {
                applynumber.setText(info.applynumber);
            }
            if (!TextUtils.isEmpty(t.views)) {
                views.setText(t.views + "");
            }
        } else {
            join.setVisibility(View.GONE);
            ll_activity.setVisibility(View.GONE);
        }
        ((TextView) view.findViewById(R.id.post_address)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 首页直接跳转列表，分类的直接返回
                int from = context.getIntent().getIntExtra(Constants.KEY_FROM_PAGE, 0);
                if (from == 0) {
                    Intent intent = new Intent(context, MyClubActivity.class);
                    intent.putExtra("name", t.getStatustitle());
                    intent.putExtra("fId", t.fid);
                    context.startActivity(intent);
                    context.finish();
                } else if (from == 1) {
                    context.finish();
                }
            }
        });
        ((TextView) view.findViewById(R.id.look_time)).setText(t.getViews());
        ((TextView) view.findViewById(R.id.care_time)).setText(String.valueOf(t.recommend_add));
        ((TextView) view.findViewById(R.id.message_time)).setText(String.valueOf(t.getReplies()));

        ImageView icon = (ImageView) view.findViewById(R.id.icon);

        ImageLoader.getInstance().displayImage(t.userface, icon);
        ((TextView) view.findViewById(R.id.name)).setText(t.author);
        ((TextView) view.findViewById(R.id.address)).setText(String.format(
                context.getString(R.string.come_from), t.address));
        ((TextView) view.findViewById(R.id.floor)).setText("楼主");
        // ((TextView) view.findViewById(R.id.time)).setText(t.addtime);
        TextView timeTV = (TextView) view.findViewById(R.id.time);

        String time = CommonUtil.formatDate();
        String year = time.substring(0, 4);

        String mTime = t.getAddtime();
        String mYear = mTime.substring(0, 4);

        String today = mTime.split(" ")[1];
        if (year.equals(mYear)) {// 说明是今年
            if (mTime.split(" ")[0].equals(time.split(" ")[0])) {// 说明是今天
                timeTV.setText(today.substring(0, 5));
            } else {
                timeTV.setText(t.getAddtime().split(" ")[0].substring(5, 10) + " "
                        + today.substring(0, 5));
            }
        } else {
            timeTV.setText(mTime.split(" ")[0]);
        }

        setReportListener(view.findViewById(R.id.jubao_louzhu), t.getPid());
        setReplyListener(view.findViewById(R.id.huifu_louzhu), String.valueOf(t.position), t.pid);
        setStartUserInfoActivityListener(icon, t.authorid, t.author, t.userface);

        LinearLayout ll_zan_icon = (LinearLayout) view.findViewById(R.id.post_detail_list_zan_icon);
        RelativeLayout p_6 = (RelativeLayout) view.findViewById(R.id.p_6);

        if (mRecommendInfos.size() == 0) {
            p_6.setVisibility(View.GONE);
        } else {
            p_6.setVisibility(View.VISIBLE);
            int size = 0;
            if (mRecommendInfos.size() < 5) {
                size = mRecommendInfos.size();
            } else {
                size = 5;
            }
            for (int i = 0; i < size; i++) {
                ImageView iv = new ImageView(context);
                if (CommonParameter.isLoadImg) {
                    ImageLoader.getInstance()
                            .displayImage(mRecommendInfos.get(i).getUserface(), iv);
                } else {
                    iv.setImageResource(R.drawable.person_loading);
                }
                iv.setScaleType(ScaleType.FIT_XY);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(70, 70);
                lp.rightMargin = 10;
                iv.setLayoutParams(lp);
                ll_zan_icon.addView(iv);
            }
        }
        return view;
    }

    /**
     * 处理是活动贴时的头部信息
     * 
     * @param t
     * @param view
     * @param iv_top_image
     * @param coverwidth
     * @param coverheight
     */
    private void item_post_top_info(final PostLandlordInfo t, View view, int coverwidth,
            int coverheight) {
        ImageView iv_top_image = (ImageView) view.findViewById(R.id.iv_top_image);
        TextView tv_starttime = (TextView) view.findViewById(R.id.tv_starttime);
        TextView tv_location = (TextView) view.findViewById(R.id.tv_location);

        iv_top_image.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                (int) ((float) CommonParameter.sScreenWidth / coverwidth * coverheight)));
        if (!TextUtils.isEmpty(t.activityinfo.coverpath)) {
            ImageLoader.getInstance().displayImage(t.activityinfo.coverpath, iv_top_image);
        } else {
            iv_top_image.setImageResource(R.drawable.picture_loading);
        }

        try {// 可能出现 java.io.FileNotFoundException: emoji.xml
            ((TextView) view.findViewById(R.id.tv_post_name)).setText(CommonUtil.convetToHtml(
                    CommonUtil.parseEmoji(t.subject), context));
            // ((TextView) view.findViewById(R.id.tv_post_name)).setText(ParseMsgUtil.convetToHtml(
            // CommonUtil.parseEmoji(CommonUtil.parseStr(t.subject)), context));
        } catch (Exception e) {
            e.printStackTrace();
        }

        tv_starttime.setText(t.activityinfo.starttimefrom);
        tv_location.setText(t.activityinfo.place);
    }

    private final String ARTICLE = "article";
    private final String IMAGE = "image";
    private final String VIDEO = "video";
    /** 引用 */
    private final String QUOTE = "quote";
    /** 引用帖子 */
    private final String QUOTEPOST = "appquotethread";
    /** 引用视频 */
    private final String QUOTEVIDEO = "webvideo";

    /**
     * 组装帖子内容体
     * 
     * @param container
     * @param list
     */
    private void parsePostContainer(final LinearLayout container,
            final List<PostLandlordMessageInfo> list, final int position) {
        container.removeAllViews();
        ArrayList<String> images = new ArrayList<String>();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                final PostLandlordMessageInfo info = list.get(i);
                if (info != null) {
                    if (info.type.equals(ARTICLE)) {// 文字
                        container.addView(getArticle(info));
                    } else if (info.type.equals(IMAGE) && info.width != 0
                            && !info.content.endsWith(".gif")) {// 图片
                        container.addView(getImageView(info, images));// &&
                        // !info.content.endsWith(".gif")
                    } else if (info.type.equals(VIDEO)) {// 视频
                        isHasVideo = true;
                        container.addView(getVideoView(info, position));
                    } else if (info.type.equals(IMAGE) && info.content.endsWith(".gif")) {// gif
                        container.addView(getGifView(info));
                    } else if (info.type.equals(QUOTE)) {// 引用
                        container.addView(getQuoteView(info));
                    } else if (info.type.equals(QUOTEVIDEO)) {// 引用视频
                        container.addView(getQuoteVideoView(info));
                    } else if (info.type.equals(QUOTEPOST)) {// 引用帖子
                        container.addView(getQuotePostView(info));
                    }
                }
            }
        }
    }

    private View getQuotePostView(final PostLandlordMessageInfo info) {
        final View view =
                LayoutInflater.from(context).inflate(R.layout.list_item_detail_quote_post, null);
        ((TextView) view.findViewById(R.id.name)).setText(CommonUtil.convetToHtml(
                CommonUtil.parseEmoji(info.appquotethreaddata.subject), context));
        // ((TextView) view.findViewById(R.id.name)).setText(info.appquotethreaddata.subject);
        if (!TextUtils.isEmpty(info.appquotethreaddata.urlthumb)) {
            ImageLoader.getInstance().displayImage(info.appquotethreaddata.urlthumb,
                    ((ImageView) view.findViewById(R.id.video_cover)));
        } else {
            view.findViewById(R.id.video_cover).setVisibility(View.GONE);
        }
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {// 跳转帖子详情
                Intent intent = new Intent(context, PostDetailActivity.class);
                intent.putExtra(Constants.KEY_POST_TID, info.appquotethreaddata.tid);
                context.startActivity(intent);
            }
        });
        return view;
    }



    private View getQuoteVideoView(final PostLandlordMessageInfo info) {
        final View view =
                LayoutInflater.from(context).inflate(R.layout.list_item_detail_quote_video, null);
        ((TextView) view.findViewById(R.id.name)).setText(info.webvideodata.body);
        ImageLoader.getInstance().displayImage(info.webvideodata.coverpath,
                ((ImageView) view.findViewById(R.id.video_cover)));
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, WebViewActivity.class);
                intent.putExtra(Constants.KEY_TOP_BAR_TITLE, "视频");
                intent.putExtra(Constants.KEY_VIDEO_URL, info.webvideodata.url);
                context.startActivity(intent);
            }
        });
        return view;
    }

    /**
     * 帖子中是否存在视频文件
     * 
     * @return
     */
    public boolean isExistVideo() {
        return isHasVideo;
    }

    public void pause(int position) {
        VideoHolder holder = mVideoHolderViews.get(position);
        if (null != holder && null != holder.myTestVideoView) {
            mPlayVideoPosition = -1;
            holder.imagePlay.setVisibility(View.VISIBLE);
            holder.progressBar.setVisibility(View.GONE);
            holder.myTestVideoView.pause();
        }
    }

    public void stopPlayback() {
        Iterator<Integer> iterator = mVideoHolderViews.keySet().iterator();
        while (iterator.hasNext()) {
            VideoHolder holder = mVideoHolderViews.get(iterator.next());
            if (null != holder.myTestVideoView) {
                mPlayVideoPosition = -1;
                holder.myTestVideoView.stopPlayback();
            }
        }
    }

    @SuppressLint("NewApi")
    private View getVideoView(final PostLandlordMessageInfo info, final int position) {
        final View view =
                LayoutInflater.from(context).inflate(R.layout.post_detail_play_vedio, null);
        final VideoHolder holder = new VideoHolder();
        holder.imagePlay = view.findViewById(R.id.previre_play);
        holder.imageCover = (ImageView) view.findViewById(R.id.preview_video);
        holder.progressBar = view.findViewById(R.id.progress);
        if (!TextUtils.isEmpty(info.coverImg)) {
            ImageLoader.getInstance().displayImage(info.coverImg, holder.imageCover);
        }

        holder.myTestVideoView = (MyTestVideoView) view.findViewById(R.id.surfaceView);

        DisplayMetrics displaymetrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        holder.myTestVideoView.setLayoutParams(new LinearLayout.LayoutParams(
                displaymetrics.widthPixels, displaymetrics.widthPixels));
        holder.imageCover.setLayoutParams(new RelativeLayout.LayoutParams(
                displaymetrics.widthPixels, displaymetrics.widthPixels));

        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                holder.myTestVideoView.initVideoView();
                play(holder, info, position);
            }
        });
        mVideoHolderViews.put(position, holder);
        return view;
    }

    class VideoHolder {
        View imagePlay;
        ImageView imageCover;
        View progressBar;
        MyTestVideoView myTestVideoView;
    }

    private void play(final VideoHolder holder, PostLandlordMessageInfo info, final int position) {
        if (holder.myTestVideoView.isPreparing()) {
            return;
        }
        if (holder.imagePlay.getVisibility() == View.GONE) {
            holder.imagePlay.setVisibility(View.VISIBLE);
        } else {
            holder.imagePlay.setVisibility(View.GONE);
        }
        if (null == holder.progressBar.getTag()) {
            holder.progressBar.setTag("a");
            holder.progressBar.setVisibility(View.VISIBLE);
        }
        holder.imagePlay.setVisibility(View.GONE);
        if (holder.myTestVideoView.isNull() || !holder.myTestVideoView.isPlaying()) {
            holder.imagePlay.setVisibility(View.GONE);

            if (mPlayVideoPosition != -1) {
                pause(mPlayVideoPosition - 1);
            }

            if (holder.myTestVideoView.isNull()) {
                holder.myTestVideoView.setVideoPath(info.content);
                holder.myTestVideoView.prepareAsync(new IRequest<Boolean>() {

                    @Override
                    public void request(Boolean t) {// 开始播放
                        // System.out.println(mFristPosition - 1 + "*****" + position);
                        // if (mFristPosition - 1 == position) {
                        // System.out.println("prepareAsync_request:" + position);
                        mPlayVideoPosition = position + 1;
                        holder.imageCover.setVisibility(View.GONE);
                        holder.progressBar.setVisibility(View.GONE);
                        holder.myTestVideoView.start();
                        // } else {
                        // holder.imagePlay.setVisibility(View.VISIBLE);
                        // }
                    }
                }, new IRequest<Boolean>() {

                    @Override
                    public void request(Boolean t) {// 播放完成
                        // if (t) {
                        // System.out.println("prepareAsync:-1");
                        mPlayVideoPosition = -1;
                        holder.imagePlay.setVisibility(View.VISIBLE);
                        // }
                    }
                });
            } else {
                mPlayVideoPosition = position + 1;
                holder.myTestVideoView.start();
                holder.imagePlay.setVisibility(View.GONE);
            }
        } else {
            System.out.println("play:-1");
            mPlayVideoPosition = -1;
            holder.myTestVideoView.pause();
            holder.imagePlay.setVisibility(View.VISIBLE);
        }
    }

    private View getGifView(PostLandlordMessageInfo info) {
        LayoutInflater inflater = LayoutInflater.from(context);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.show_gif, null);

        final WebView gifView = (WebView) layout.findViewById(R.id.showgif);


        if (info.height > 0 && info.width > 0) {

            LayoutParams lp =
                    new LayoutParams(LayoutParams.MATCH_PARENT, CommonParameter.sScreenWidth
                            * info.height / info.width);
            layout.setLayoutParams(lp);
        } else {
            LayoutParams lp =
                    new LayoutParams(LayoutParams.MATCH_PARENT, CommonParameter.sScreenWidth);
            layout.setLayoutParams(lp);
        }
        //
        // gifView.setLayoutParams(lp);


        // // 设置可以支持缩放
        // gifView.getSettings().setSupportZoom(true);
        // // 设置出现缩放工具
        // gifView.getSettings().setBuiltInZoomControls(true);
        // // 扩大比例的缩放
        // gifView.getSettings().setUseWideViewPort(true);
        // // 自适应屏幕
        gifView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        gifView.getSettings().setLoadWithOverviewMode(true);

        int screenDensity = context.getResources().getDisplayMetrics().densityDpi;
        WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.MEDIUM;
        switch (screenDensity) {
            case DisplayMetrics.DENSITY_LOW:
                zoomDensity = WebSettings.ZoomDensity.CLOSE;
                break;
            case DisplayMetrics.DENSITY_MEDIUM:
                zoomDensity = WebSettings.ZoomDensity.MEDIUM;
                break;
            case DisplayMetrics.DENSITY_HIGH:
                zoomDensity = WebSettings.ZoomDensity.FAR;
                break;
        }
        gifView.getSettings().setDefaultZoom(zoomDensity);
        gifView.getSettings().setSupportZoom(false);


        gifView.loadDataWithBaseURL(null, "<center><img src=" + info.content + "></center>",
                "text/html", "utf-8", null);

        return layout;
    }

    /**
     * 引用
     * 
     * @param info
     * @return
     */
    private View getQuoteView(PostLandlordMessageInfo info) {
        View view = View.inflate(context, R.layout.item_post_yinyong, null);
        ((TextView) view.findViewById(R.id.name)).setText(CommonUtil.convetToHtml(
                CommonUtil.parseEmoji(String.format("“%s”", info.content)), context));
        return view;
    }

    /**
     * 文本
     * 
     * @param info
     * @return
     */
    private View getArticle(PostLandlordMessageInfo info) {
        TextView tv = (TextView) View.inflate(context, R.layout.item_post_article, null);

        // tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setTextColor(context.getResources().getColor(R.color.post_detail_text_color));
        SpannableStringBuilder ssb =
                CommonUtil.convetToHtml(CommonUtil.parseEmoji(info.content), context);
        // ssb = new InputRegular(context).parse(ssb);
        tv.setText(ssb);
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        lp.topMargin = MARGINTOP;
        tv.setLayoutParams(lp);
        return tv;
    }

    private final int MARGINTOP = 8;
    private TextView praise;

    /**
     * 图片
     * 
     * @param info
     * @return
     */
    private View getImageView(final PostLandlordMessageInfo info, final ArrayList<String> images) {
        ImageView imageView = new ImageView(context);
        imageView.setScaleType(ScaleType.FIT_XY);
        if (info.width > 0) {
            LayoutParams lp =
                    new LayoutParams(LayoutParams.MATCH_PARENT, CommonParameter.sScreenWidth
                            * info.height / info.width);
            lp.topMargin = MARGINTOP;
            imageView.setLayoutParams(lp);
        }
        if (CommonParameter.isLoadImg) {
            ImageLoader.getInstance().displayImage(info.content, imageView);
        } else {
            imageView.setBackgroundResource(R.drawable.picture_loading);
        }
        images.add(info.content);
        imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                MxxBlurView mxxB = new MxxBlurView(context);
                mxxB.drawBlurOnce();
                Intent intent = new Intent(context, PostImageActivity.class);
                intent.putStringArrayListExtra(Constants.KEY_PHOTOS, images);
                // 设置当前的偏移量
                for (int i = 0; i < images.size(); i++) {
                    if (info.content.equals(images.get(i))) {
                        intent.putExtra(Constants.KEY_CURRENT_INDEX, i);
                        break;
                    }
                }
                context.startActivity(intent);
            }
        });
        return imageView;
    }

    // **********************************************************************
    public long parserDate(String str) {
        try {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return format.parse(str).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
    }

    private class JoinActivitySuccessReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // join.setBackgroundResource(R.drawable.join_noclick);
            // join.setClickable(false);
            if (mPostLandlordMessageInfo != null && mPostLandlordMessageInfo.activityinfo != null) {
                mPostLandlordMessageInfo.activityinfo.isapply = "1";
                notifyDataSetChanged();
            }
        }
    }

    public JoinActivitySuccessReceiver getSuccessReceiver() {
        return successReceiver != null ? successReceiver : null;
    }
}
